package com.fafa.pos.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.*;
import android.net.Uri;
import android.os.*;
import android.support.annotation.UiThread;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.widget.*;
import com.fafa.pos.R;
import com.fafa.pos.biz.ComplexBiz;
import com.fafa.pos.dao.*;
import com.fafa.pos.dao.impl.*;
import com.fafa.pos.pojo.CardInfo;
import com.fafa.pos.pojo.Config;
import com.fafa.pos.pojo.ConsumeInfo;
import com.fafa.pos.pojo.VipInfo;
import com.fafa.pos.util.*;
import com.fafa.pos.util.newland.ISOUtils;
import com.fafa.pos.vo.CurUser;
import com.fafa.pos.vo.Status;
import com.fafa.pos.vo.WSResult;
import com.nld.cloudpos.aidl.AidlDeviceService;
import com.nld.cloudpos.aidl.printer.AidlPrinter;
import com.nld.cloudpos.aidl.printer.AidlPrinterListener;
import com.nld.cloudpos.aidl.printer.PrintItemObj;
import com.nld.cloudpos.aidl.rfcard.AidlRFCard;
import com.nld.cloudpos.data.PrinterConstant;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

public class MainActivity extends Activity {


    private SharedPreferencesHelper sharedPreferencesHelper;
    private String userCode;

    //复杂业务
    private ComplexBiz complexBiz;

    //Dao相关
    private DBUtil dbUtil;
    private IUserInfoDao userInfoDao;
    private IConsumeInfoDao consumeInfoDao;
    private IConfigDao configDao;
    private ICardInfoDao cardInfoDao;
    private IVipInfoDao vipInfoDao;

    //提示信息
    private TextView consumeType;//正常模式、固定金额模式
    private TextView mainHint;
    private LinearLayout keyBord;//键盘
    //快捷键
    private TextView quickKey1;
    private TextView quickKey2;
    private TextView quickKey3;
    private TextView quickKey4;
    //数字
    private TextView number0;
    private TextView number1;
    private TextView number2;
    private TextView number3;
    private TextView number4;
    private TextView number5;
    private TextView number6;
    private TextView number7;
    private TextView number8;
    private TextView number9;
    //运算符
    private TextView operate_plus;
    private TextView operate_multiply;
    private TextView operate_dot;
    private TextView operate_equal;
    //结果
    private TextView operate_result;
    private String payMoney;
    //清除结果键
    private TextView clearBtn;
    //是否要清掉之间的运算式
    private boolean isClearOperateResult = false;
    //功能键
    private RelativeLayout balanceInquire;//余额查询
    private TextView balanceInquireDes;
    private ImageView balanceInquireImg;
    private RelativeLayout fixedMoney;//固定金额
    private TextView fixedMoneyDes;
    private ImageView fixedMoneyImg;
    private View fixedMoneyBorder1;
    private View fixedMoneyBorder2;
    private RelativeLayout functionSetting;//功能设置
    private ImageView functionSettingImg;
    private TextView functionSettingDes;
    private boolean isFixedMoney = false;


    //事件相关
    private View.OnClickListener balanceInquireDo;
    private View.OnClickListener functionSettingDo;


    private final String TAG = "newLand";
    private int interval;//同一张卡两次刷卡之间的最短时间
    private AidlRFCard aidlRFCard;


    private static SoundPool soundPool;
    private HashMap<Integer,Integer> sounddata;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //加入退出管理
        MyActivityManager.getInstance().addActivity(this);

        initDaoAndBiz();
        initView();
        initEvent();

        bindService(new Intent("nld_cloudpos_device_service"), serviceConnection,
                Context.BIND_AUTO_CREATE);

        interval = Integer.parseInt(configDao.getConfig().getProperties().get("scanIntervalTime"));




        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).setUsage(AudioAttributes.USAGE_MEDIA).build();
        soundPool = new SoundPool.Builder().setMaxStreams(2).setAudioAttributes(audioAttributes).build();
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                System.out.println("加载音效----------------------" + sampleId);
            }
        });

        sounddata = new HashMap<Integer,Integer>();
        sounddata.put(1,soundPool.load(MainActivity.this,R.raw.di,1));
        sounddata.put(2,soundPool.load(MainActivity.this,R.raw.di_error,1));
        sounddata.put(3,soundPool.load(MainActivity.this,R.raw.press_key_sound,1));

    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
        if (timerTask != null) {//先把上次结束掉
            timerTask.cancel();
            timerTask = null;
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initDaoAndBiz() {
        dbUtil = new DBUtil(getApplicationContext().getFilesDir().getAbsoluteFile() + "/pos.db");
        userInfoDao = new UserInfoDaoImpl(dbUtil);
        consumeInfoDao = new ConsumeInfoDaoImpl(dbUtil);
        complexBiz = new ComplexBiz(dbUtil);
        configDao = new ConfigDaoImpl(dbUtil);
        cardInfoDao = new CardInfoDaoImpl(dbUtil);
        vipInfoDao = new VipInfoDaoImpl(dbUtil);
    }


    /**
     * newLand服务连接
     */
    private AidlDeviceService aidlDeviceService;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "bind device service");
            aidlDeviceService = AidlDeviceService.Stub.asInterface(service);
            try {
                aidlRFCard = AidlRFCard.Stub.asInterface(aidlDeviceService.getRFIDReader());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "unbind device service");
            aidlDeviceService = null;
        }
    };

    /**
     * 初始化View
     */
    private void initView() {
        sharedPreferencesHelper = new SharedPreferencesHelper(
                MainActivity.this, "PosUserInfo");  //实例化sharedPreferencesHelper工具类
        userCode = sharedPreferencesHelper.getSharedPreference("userCode", "").toString().trim();//获取userCode

        keyBord = (LinearLayout) findViewById(R.id.keyBord);

        consumeType = (TextView) findViewById(R.id.type);

        mainHint = (TextView) findViewById(R.id.main_hint);

        quickKey1 = (TextView) findViewById(R.id.quickKey1);
        quickKey2 = (TextView) findViewById(R.id.quickKey2);
        quickKey3 = (TextView) findViewById(R.id.quickKey3);
        quickKey4 = (TextView) findViewById(R.id.quickKey4);
        number0 = (TextView) findViewById(R.id.number0);
        number1 = (TextView) findViewById(R.id.number1);
        number2 = (TextView) findViewById(R.id.number2);
        number3 = (TextView) findViewById(R.id.number3);
        number4 = (TextView) findViewById(R.id.number4);
        number5 = (TextView) findViewById(R.id.number5);
        number6 = (TextView) findViewById(R.id.number6);
        number7 = (TextView) findViewById(R.id.number7);
        number8 = (TextView) findViewById(R.id.number8);
        number9 = (TextView) findViewById(R.id.number9);
        operate_plus = (TextView) findViewById(R.id.operate_plus);
        operate_multiply = (TextView) findViewById(R.id.operate_multiply);
        operate_dot = (TextView) findViewById(R.id.operate_dot);
        operate_equal = (TextView) findViewById(R.id.operate_equal);
        operate_result = (TextView) findViewById(R.id.operate_result);
        clearBtn = (TextView) findViewById(R.id.clearBtn);
        balanceInquire = (RelativeLayout) findViewById(R.id.balance_inquire);
        balanceInquireDes = (TextView) findViewById(R.id.balance_inquire_des);
        balanceInquireImg = (ImageView) findViewById(R.id.balance_inquire_img);
        fixedMoney = (RelativeLayout) findViewById(R.id.fixed_money);
        fixedMoneyDes = (TextView) findViewById(R.id.fixed_money_des);
        fixedMoneyImg = (ImageView) findViewById(R.id.fixed_money_img);
        functionSetting = (RelativeLayout) findViewById(R.id.function_setting);
        fixedMoneyBorder1 = (View) findViewById(R.id.fixed_money_border1);
        fixedMoneyBorder2 = (View) findViewById(R.id.fixed_money_border2);
        functionSettingImg = (ImageView) findViewById(R.id.function_setting_img);
        functionSettingDes = (TextView) findViewById(R.id.function_setting_des);

        List<ConsumeInfo> consumeInfos = consumeInfoDao.getAllOffLineConsumeInfo();
        consumeType.setText((Status.getStatus().isOffLine() ? "离线" : "在线") + "·正常模式(" + consumeInfos.size() + ")");


        if(Status.getStatus().isOffLine()||isFixedMoney){
            initBalanceInquire(true);
        }else {
            initBalanceInquire(false);
        }


        if(isFixedMoney){
            fixedMoney.setBackgroundResource(R.color.LoginBlue);
            fixedMoneyImg.setBackgroundResource(R.drawable.fixed_money_active);
            fixedMoneyDes.setText("取消固定金额");
            fixedMoneyDes.setTextColor(getResources().getColor(R.color.white));
            fixedMoneyBorder1.setVisibility(View.INVISIBLE);
            fixedMoneyBorder2.setVisibility(View.INVISIBLE);
            keyBord.setAlpha(0.5f);
        }else{

            keyBord.setAlpha(1);
            clear();
            fixedMoneyImg.setBackgroundResource(R.drawable.fixed_money);
            fixedMoney.setBackgroundResource(R.color.gray);
            fixedMoneyDes.setTextColor(getResources().getColor(R.color.LoginBlue));
            fixedMoneyDes.setText("固定金额");
            fixedMoneyBorder1.setVisibility(View.VISIBLE);
            fixedMoneyBorder2.setVisibility(View.VISIBLE);
        }


        Config config = configDao.getConfig();
        if (config.getProperties().get("quickKey1") != null) {
            quickKey1.setText(config.getProperties().get("quickKey1").trim());
        }
        if (config.getProperties().get("quickKey2") != null) {
            quickKey2.setText(config.getProperties().get("quickKey2").trim());
        }
        if (config.getProperties().get("quickKey3") != null) {
            quickKey3.setText(config.getProperties().get("quickKey3").trim());
        }
        if (config.getProperties().get("quickKey4") != null) {
            quickKey4.setText(config.getProperties().get("quickKey4").trim());
        }
    }

    /**
     * 初始化余额查询btn
     * @param isBan 是否禁止
     */
    private void initBalanceInquire(boolean isBan) {
        if (isBan) {
            balanceInquire.setOnClickListener(null);
            balanceInquireDes.setTextColor(getResources().getColor(R.color.ban));
            balanceInquireImg.setBackgroundResource(R.drawable.balance_inquire_ban);
            System.out.println("余额查询--关闭");

        } else {
            balanceInquire.setOnClickListener(balanceInquireDo);
            balanceInquireDes.setTextColor(getResources().getColor(R.color.LoginBlue));
            balanceInquireImg.setBackgroundResource(R.drawable.balance_inquire);
            System.out.println("余额查询--开启");
        }
    }

    /**
     * 初始化功能设置btn
     * @param isBan 是否禁止
     */
    private void initFunctionSetting(boolean isBan) {
        if (isBan) {
            functionSetting.setOnClickListener(null);
            functionSettingDes.setTextColor(getResources().getColor(R.color.ban));
            functionSettingImg.setBackgroundResource(R.drawable.function_setting_ban);
            System.out.println("余额查询--关闭");

        } else {
            functionSetting.setOnClickListener(functionSettingDo);
            functionSettingDes.setTextColor(getResources().getColor(R.color.LoginBlue));
            functionSettingImg.setBackgroundResource(R.drawable.function_setting);
            System.out.println("余额查询--开启");
        }
    }

    private void initEvent() {

        //设置mainHint为可滑动的
        mainHint.setMovementMethod(ScrollingMovementMethod.getInstance());

        //离在线模式切换
        /*consumeType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Status.getStatus().setOffLine(!Status.getStatus().isOffLine());
                consumeType.setText((Status.getStatus().isOffLine() ? "离线" : "在线")+consumeType.getText().toString().substring(2));

                initBalanceInquire(Status.getStatus().isOffLine());
            }
        });*/


        //普通按钮触摸事件
        final View.OnTouchListener ordinaryTouch = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                TextView btn = (TextView) v;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP://松开事件发生后执行代码的区域
                        btn.setBackgroundResource(R.drawable.btn_right_border);
                        pressKey(btn.getId());
                        break;
                    case MotionEvent.ACTION_DOWN://按住事件发生后执行代码的区域
                        btn.setBackgroundResource(R.color.btnActive);
                        break;
                    default:
                        break;
                }
                return true;
            }
        };
        //运算按钮触摸事件
        final View.OnTouchListener operateTouch = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                TextView btn = (TextView) v;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP://松开事件发生后执行代码的区域
                        btn.setBackgroundResource(R.drawable.btn_operate_border);
                        pressKey(btn.getId());
                        break;
                    case MotionEvent.ACTION_DOWN://按住事件发生后执行代码的区域
                        btn.setBackgroundResource(R.color.btnActive);
                        break;
                    default:
                        break;
                }
                return true;
            }
        };
        //等号触摸事件
        final View.OnTouchListener submitTouch = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                TextView btn = (TextView) v;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP://松开事件发生后执行代码的区域
                        btn.setBackgroundResource(R.color.LoginBlue);
                        pressKey(btn.getId());
                        break;
                    case MotionEvent.ACTION_DOWN://按住事件发生后执行代码的区域
                        btn.setBackgroundResource(R.color.LoginBluePlus);
                        break;
                    default:
                        break;
                }
                return true;
            }
        };

        quickKey1.setOnTouchListener(ordinaryTouch);
        quickKey2.setOnTouchListener(ordinaryTouch);
        quickKey3.setOnTouchListener(ordinaryTouch);
        quickKey4.setOnTouchListener(ordinaryTouch);
        number0.setOnTouchListener(ordinaryTouch);
        number1.setOnTouchListener(ordinaryTouch);
        number2.setOnTouchListener(ordinaryTouch);
        number3.setOnTouchListener(ordinaryTouch);
        number4.setOnTouchListener(ordinaryTouch);
        number5.setOnTouchListener(ordinaryTouch);
        number6.setOnTouchListener(ordinaryTouch);
        number7.setOnTouchListener(ordinaryTouch);
        number8.setOnTouchListener(ordinaryTouch);
        number9.setOnTouchListener(ordinaryTouch);
        operate_plus.setOnTouchListener(operateTouch);
        operate_multiply.setOnTouchListener(operateTouch);
        operate_dot.setOnTouchListener(operateTouch);
        operate_equal.setOnTouchListener(submitTouch);
        clearBtn.setOnTouchListener(operateTouch);


        functionSettingDo = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                playSound(3,0);

                if(timerTask!=null){
                    timerTask.cancel();
                    timerTask = null;
                }

                Intent intent = new Intent(MainActivity.this, MoreActivity.class);
                startActivity(intent);
            }
        };


        if(isFixedMoney){ //固定金额下
            //功能设置
            functionSetting.setOnClickListener(null);
        }else{
            //功能设置
            functionSetting.setOnClickListener(functionSettingDo);
        }


        //固定金额
        fixedMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                playSound(3,0);

                isFixedMoney = !isFixedMoney;
                if (isFixedMoney) {
                    mainHint.setText("请输入固定收款金额,并确认");
                    fixedMoney.setBackgroundResource(R.color.LoginBlue);
                    fixedMoneyImg.setBackgroundResource(R.drawable.fixed_money_active);
                    fixedMoneyDes.setText("取消固定金额");
                    fixedMoneyDes.setTextColor(getResources().getColor(R.color.white));
                    fixedMoneyBorder1.setVisibility(View.INVISIBLE);
                    fixedMoneyBorder2.setVisibility(View.INVISIBLE);

                    List<ConsumeInfo> consumeInfos = consumeInfoDao.getAllOffLineConsumeInfo();
                    consumeType.setText((Status.getStatus().isOffLine() ? "离线" : "在线") + "·固定金额模式(" + consumeInfos.size() + ")");

                    //禁掉余额查询
                    initBalanceInquire(true);
                    //禁掉功能设置
                    initFunctionSetting(true);
                } else {//取消固定金额  键盘重新绑定事件 开启余额查询功能
                    if(!Status.getStatus().isOffLine()){
                        initBalanceInquire(false);
                    }
                    initFunctionSetting(false);

                    List<ConsumeInfo> consumeInfos = consumeInfoDao.getAllOffLineConsumeInfo();
                    consumeType.setText((Status.getStatus().isOffLine() ? "离线" : "在线") + "·正常模式(" + consumeInfos.size() + ")");

                    if (timerTask != null) {//结束掉当前消费
                        timerTask.cancel();
                        timerTask = null;
                    }

                    keyBord.setAlpha(1);
                    clear();

                    isClearOperateResult = false;

                    fixedMoneyImg.setBackgroundResource(R.drawable.fixed_money);
                    fixedMoney.setBackgroundResource(R.color.gray);
                    fixedMoneyDes.setTextColor(getResources().getColor(R.color.LoginBlue));
                    fixedMoneyDes.setText("固定金额");
                    fixedMoneyBorder1.setVisibility(View.VISIBLE);
                    fixedMoneyBorder2.setVisibility(View.VISIBLE);

                    quickKey1.setOnTouchListener(ordinaryTouch);
                    quickKey2.setOnTouchListener(ordinaryTouch);
                    quickKey3.setOnTouchListener(ordinaryTouch);
                    quickKey4.setOnTouchListener(ordinaryTouch);
                    number0.setOnTouchListener(ordinaryTouch);
                    number1.setOnTouchListener(ordinaryTouch);
                    number2.setOnTouchListener(ordinaryTouch);
                    number3.setOnTouchListener(ordinaryTouch);
                    number4.setOnTouchListener(ordinaryTouch);
                    number5.setOnTouchListener(ordinaryTouch);
                    number6.setOnTouchListener(ordinaryTouch);
                    number7.setOnTouchListener(ordinaryTouch);
                    number8.setOnTouchListener(ordinaryTouch);
                    number9.setOnTouchListener(ordinaryTouch);
                    operate_plus.setOnTouchListener(operateTouch);
                    operate_multiply.setOnTouchListener(operateTouch);
                    operate_dot.setOnTouchListener(operateTouch);
                    operate_equal.setOnTouchListener(submitTouch);
                    clearBtn.setOnTouchListener(operateTouch);
                }
            }
        });

        balanceInquireDo = new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                playSound(3,0);

                mainHint.setText("请刷卡");

                if (timerTask != null) {//如果有读卡逻辑，先结束掉
                    timerTask.cancel();
                    timerTask = null;
                }


                readCard(new ReadCardCallBack() {
                    @Override
                    public void execute(String cardNo,String uuid) {
                        System.out.println("~~~~~~~~~~~~start余额查询逻辑~~~~~~~~~~~~~");
                        //余额查询
                        Map<String, Object> parameters = new HashMap<>();
                        parameters.put("strCardCode", cardNo.trim());

                        Config config = configDao.getConfig();
                        SoapObject so = WebServiceUtil.getResponse(config, "GetBalanceInfo", parameters, 1000 * 15);

                        if (so != null) {
                            SoapPrimitive sp = (SoapPrimitive) so.getProperty("GetBalanceInfoResult");
                            WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());

                            System.out.println("结果响应码：" + wsResult.getResultCode());

                            if (wsResult.getResultCode() == 0) {

                                String hint = "";
                                CardInfo cardInfo = cardInfoDao.getCard(cardNo);
                                if (cardInfo != null) {
                                    VipInfo vipInfo = vipInfoDao.getVipInfo(cardInfo.getVipId());
                                    if (vipInfo != null) {
                                        consumeInfo.setVipName(vipInfo.getVipName());
                                        hint+="会员号:"+vipInfo.getVipId()+"\n";
                                        hint+="姓名:"+vipInfo.getVipName()+"\n";
                                    }
                                }
                                List<Map<String, Object>> list = (List<Map<String, Object>>) wsResult.getResultValues().get("List");
                                for (int i = 0; i < list.size(); i++) {
                                    hint += list.get(i).get("ACCT_NAME") + ":" + list.get(i).get("NOW_AMT") + "\n";
                                }
                                Message msg = new Message();
                                msg.what = 2;
                                msg.obj = hint;

                                setMainHint(msg);
                                //播放成功蜂鸣
                                playSound(1,0);

                            } else {
                                Message msg = new Message();
                                msg.what = 7;
                                msg.obj = wsResult.getResultValues().get("message").toString();
                                //播放失败蜂鸣
                                playSound(2,0);
                                setMainHint(msg);

                            }
                        } else {
                            Message msg = new Message();
                            msg.what = 7;
                            msg.obj = "连接超时";
                            //播放失败蜂鸣
                            playSound(2,0);
                            setMainHint(msg);
                        }
                        timerTask.cancel();
                        System.out.println("~~~~~~~~~~~~end余额查询逻辑~~~~~~~~~~~~~");
                    }
                });
            }
        };

        //余额查询 事件绑定
        if (Status.getStatus().isOffLine()||isFixedMoney) {
            balanceInquire.setOnClickListener(null);
        } else {
            balanceInquire.setOnClickListener(balanceInquireDo);
        }
    }

    private void pressKey(int keyId) {


        playSound(3,0);

        switch (keyId) {
            case R.id.number0:
                pressNumber("0");
                break;
            case R.id.number1:
                pressNumber("1");
                break;
            case R.id.number2:
                pressNumber("2");
                break;
            case R.id.number3:
                pressNumber("3");
                break;
            case R.id.number4:
                pressNumber("4");
                break;
            case R.id.number5:
                pressNumber("5");
                break;
            case R.id.number6:
                pressNumber("6");
                break;
            case R.id.number7:
                pressNumber("7");
                break;
            case R.id.number8:
                pressNumber("8");
                break;
            case R.id.number9:
                pressNumber("9");
                break;
            case R.id.operate_dot:
                pressDot(".");
                break;
            case R.id.operate_plus:
                pressOperate("+");
                break;
            case R.id.operate_multiply:
                pressOperate("x");
                break;
            case R.id.operate_equal:
                pressOperate("=");
                break;
            case R.id.clearBtn:
                clear();
                break;
            case R.id.quickKey1:
                pressQuickKey(quickKey1.getText().toString().trim());
                break;
            case R.id.quickKey2:
                pressQuickKey(quickKey2.getText().toString().trim());
                break;
            case R.id.quickKey3:
                pressQuickKey(quickKey3.getText().toString().trim());
                break;
            case R.id.quickKey4:
                pressQuickKey(quickKey4.getText().toString().trim());
                break;
            default:
                break;
        }
    }

    private void clear() {
        operate_result.setText("0.00");
        mainHint.setText("需付款: ¥0.00");
        mainHint.scrollTo(0,0);
        mainHint.setHeight(mainHint.getLineHeight());
        isClearOperateResult = false;
    }

    /**
     * 按快捷键
     * @param keyValue 键值
     */
    private void pressQuickKey(String keyValue) {

        if (!isClearOperateResult) { //是否清除现有结果

            String curText = operate_result.getText().toString();
            //是否包含运算符
            if (curText.contains("+") || (curText.contains("-") && curText.charAt(0) != '-') || curText.contains("x")) {

                //最后一位是否为运算符
                if (curText.charAt(operate_result.getText().length() - 1) == '+'
                        || curText.charAt(operate_result.getText().length() - 1) == 'x'
                        || curText.charAt(operate_result.getText().length() - 1) == '-') {
                    operate_result.setText(curText + keyValue);//拼接
                } else {//包含加减乘除

                    //1.计算
                    execute();
                    //2.加法拼接
                    operate_result.setText(operate_result.getText() + "+" + keyValue);
                }

            } else {
                operate_result.setText(keyValue + "+");//快捷键+
            }
        } else {
            operate_result.setText(keyValue + "+");//快捷键+
        }
        isClearOperateResult = false;//下次按键不清除

    }

    /**
     * 按数字键
     * @param keyValue 键值
     */
    private void pressNumber(String keyValue) {
        //是否清除当前结果
        if (!isClearOperateResult && !operate_result.getText().toString().equals("0.00") && !operate_result.getText().toString().equals("0")) {

            boolean isAppend = false;

            String curText = operate_result.getText().toString();

            if (curText.contains("+") || (curText.contains("-") && curText.charAt(0) != '-') || curText.contains("x")) {

                if (curText.charAt(operate_result.getText().length() - 1) == '+'
                        || curText.charAt(operate_result.getText().length() - 1) == 'x'
                        || curText.charAt(operate_result.getText().length() - 1) == '-') {
                    isAppend = true;
                } else {
                    if (curText.contains("+")) {
                        curText = curText.substring(curText.lastIndexOf("+") + 1);
                    } else if (curText.contains("x")) {
                        curText = curText.substring(curText.lastIndexOf("x") + 1);
                    } else if (curText.contains("-")) {
                        curText = curText.substring(curText.lastIndexOf("-") + 1);
                    }
                }
            }
            if (curText.contains(".")) {
                if (curText.substring(curText.lastIndexOf(".") + 1).length() < 2) {
                    if (curText.length() < 12) {
                        isAppend = true;
                    }
                }
            } else {
                if (curText.length() < 9) {
                    isAppend = true;
                }

            }
            if (isAppend) {
                operate_result.setText(operate_result.getText() + keyValue);
            }

        } else {
            operate_result.setText(keyValue);
            isClearOperateResult = false;
        }
        isClearOperateResult = false;
    }

    /**
     * 按小数点
     * @param keyValue
     */
    private void pressDot(String keyValue) {
        if (!isClearOperateResult) {
            String curText = operate_result.getText().toString();
            if (curText.contains("+") || curText.contains("-") || curText.contains("x")) {
                if (curText.charAt(operate_result.getText().length() - 1) == '+'
                        || curText.charAt(operate_result.getText().length() - 1) == 'x'
                        || curText.charAt(operate_result.getText().length() - 1) == '-') {
                    operate_result.setText(operate_result.getText() + "0" + keyValue);
                } else if (!curText.substring(curText.length() - 1).equals(".")) {

                    String paramB = "";
                    if (curText.contains("+")) {
                        paramB = curText.substring(curText.indexOf("+") + 1);
                    } else if (curText.contains("x")) {
                        paramB = curText.substring(curText.indexOf("x") + 1);
                    } else if (curText.contains("-")) {
                        paramB = curText.substring(curText.indexOf("-") + 1);
                    }
                    if (!paramB.contains(".")) {
                        operate_result.setText(operate_result.getText() + keyValue);
                    }
                }
            } else {
                if (!curText.contains(".")) {
                    operate_result.setText(operate_result.getText() + keyValue);
                }
            }
        } else {
            operate_result.setText("0.");
        }
        isClearOperateResult = false;
    }

    /**
     * 按运算键
     * +、-、*    =
     * @param keyValue
     */
    //-570.0-0+    -98x7-    -98x
    private void pressOperate(String keyValue) {

        //若最后一位为'.' 则去掉
        if (operate_result.getText().toString().charAt(operate_result.getText().toString().length() - 1) == '.') {
            operate_result.setText(operate_result.getText().toString().substring(0, operate_result.getText().toString().length() - 1));
        }

        String curText = operate_result.getText().toString();
        if (keyValue.equals("=")) {
            if (curText.contains("+") || curText.contains("-") || curText.contains("x")) {

                if (curText.charAt(operate_result.getText().length() - 1) == '+'
                        || curText.charAt(operate_result.getText().length() - 1) == 'x'
                        || curText.charAt(operate_result.getText().length() - 1) == '-') {
                    operate_result.setText(curText.substring(0, curText.length() - 1));
                    isClearOperateResult = false;
                } else {
                    execute();
                }
            }

            //若最后一位为小数点，则去掉
            if (operate_result.getText().toString().charAt(operate_result.getText().toString().length() - 1) == '.') {
                operate_result.setText(operate_result.getText().toString().substring(0, operate_result.getText().toString().length() - 1));
            }
            String result = operate_result.getText().toString();
            if (result.contains(".")) {//保留两位小数

                //至多保留两位小数
                if (result.substring(result.indexOf(".") + 1).length() > 2 && !result.contains("e") && !result.contains("E")) {
                    result = result.substring(0, result.indexOf(".") + 3);
                }
                if (result.substring(result.indexOf(".") + 1).length() == 1) {//有一位小数
                    result += "0";
                }
            } else {
                result += ".00";
            }
            operate_result.setText(result);

            if (!isFixedMoney) {
                mainHint.setText("需付款: ¥" + operate_result.getText());
            }

            if (Double.parseDouble(operate_result.getText().toString()) <= 0) {
                Toast toast = Toast.makeText(MainActivity.this, "付款金额必须大于0", Toast.LENGTH_SHORT);
                MyToast.showMyToast(toast, 1000);
            } else {//付款金额大于0
                mainHint.setText("需付款: ¥" + operate_result.getText() + "\n\n请刷卡");

                payMoney = operate_result.getText().toString();

                if (isFixedMoney) {//固定金额循环等待刷卡付钱,每次运行完等待1s再继续运行


                    //禁掉键盘事件
                    keyBord.setAlpha(0.5f);
                    quickKey1.setOnTouchListener(null);
                    quickKey2.setOnTouchListener(null);
                    quickKey3.setOnTouchListener(null);
                    quickKey4.setOnTouchListener(null);
                    number0.setOnTouchListener(null);
                    number1.setOnTouchListener(null);
                    number2.setOnTouchListener(null);
                    number3.setOnTouchListener(null);
                    number4.setOnTouchListener(null);
                    number5.setOnTouchListener(null);
                    number6.setOnTouchListener(null);
                    number7.setOnTouchListener(null);
                    number8.setOnTouchListener(null);
                    number9.setOnTouchListener(null);
                    operate_plus.setOnTouchListener(null);
                    operate_multiply.setOnTouchListener(null);
                    operate_dot.setOnTouchListener(null);
                    operate_equal.setOnTouchListener(null);
                    clearBtn.setOnTouchListener(null);

                    pay();

                    /*new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (isFixedMoney) {
                                System.out.println("运行一次");
                                pay();
                            } else {
                                this.cancel();
                            }
                        }
                    }, 0, 4000);*/

                } else {
                    pay();
                }
            }

            isClearOperateResult = true;
        } else {
            if (curText.contains("+") || curText.contains("-") || curText.contains("x")) {
                if (curText.contains("-")) {
                    String temp = curText.substring(1);
                    if (curText.indexOf("-") != 0 || (curText.indexOf("-") == 0 && (temp.contains("+") || temp.contains("-") || temp.contains("x")))) {

                        if (curText.charAt(operate_result.getText().length() - 1) == '+'
                                || curText.charAt(operate_result.getText().length() - 1) == 'x'
                                || curText.charAt(operate_result.getText().length() - 1) == '-') {
                            operate_result.setText(curText.substring(0, curText.length() - 1) + keyValue);
                        } else {
                            //先计算
                            execute();
                            isClearOperateResult = false;
                            //然后再拼接运算符
                            operate_result.setText(operate_result.getText().toString() + keyValue);
                        }
                    } else {
                        operate_result.setText(operate_result.getText().toString() + keyValue);
                    }

                } else {
                    if (curText.charAt(operate_result.getText().length() - 1) == '+'
                            || curText.charAt(operate_result.getText().length() - 1) == 'x'
                            || curText.charAt(operate_result.getText().length() - 1) == '-') {
                        operate_result.setText(curText.substring(0, curText.length() - 1) + keyValue);
                    } else {
                        //先计算
                        execute();
                        isClearOperateResult = false;
                        //然后再拼接运算符
                        operate_result.setText(operate_result.getText().toString() + keyValue);
                    }
                }
            } else if (curText.length() > 0) {
                operate_result.setText(curText + keyValue);
            }
            isClearOperateResult = false;
        }

    }

    /**
     * 计算结果
     *
     * 保证当前运算式的格式为  A x B、A - B、A + B
     * -3-3   -3x4   -3+4
     */
    private void execute() {

        //若最后一位为'.' 则去掉
        if (operate_result.getText().toString().charAt(operate_result.getText().toString().length() - 1) == '.') {
            operate_result.setText(operate_result.getText().toString().substring(0, operate_result.getText().toString().length() - 1));
        }

        String curText = operate_result.getText().toString();
        String result = "";


        if (curText.contains("+")) {
            BigDecimal paramA = new BigDecimal(curText.substring(0, curText.indexOf("+")));
            BigDecimal paramB = new BigDecimal(curText.substring(curText.indexOf("+") + 1));

            result = paramA.add(paramB).toString();
        } else if (curText.contains("x")) {
            BigDecimal paramA = new BigDecimal(curText.substring(0, curText.indexOf("x")));
            BigDecimal paramB = new BigDecimal(curText.substring(curText.indexOf("x") + 1));

            result = paramA.multiply(paramB).toString();
        } else if (curText.contains("-")) {
            BigDecimal paramA = new BigDecimal(curText.substring(0, curText.lastIndexOf("-")));
            BigDecimal paramB = new BigDecimal(curText.substring(curText.lastIndexOf("-") + 1));

            result = paramA.subtract(paramB).toString();
        }

        System.out.println(result);
        if (result.contains(".")) {//保留两位小数

            //至多保留两位小数
            if (result.substring(result.indexOf(".") + 1).length() > 2 && !result.contains("e") && !result.contains("E")) {
                result = result.substring(0, result.indexOf(".") + 3);
            }
            if (result.substring(result.indexOf(".") + 1).length() == 1) {//有一位小数
                result += "0";
            }
        } else {
            result += ".00";
        }

        operate_result.setText(result);
        isClearOperateResult = true;
    }


    /**
     * 2秒之内按两次返回键退出
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    //记录返回按键的时间
    private long exitTime = 0;

    /**
     * 程序退出
     */
    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast toast = Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT);
            MyToast.showMyToast(toast, 1000);
            exitTime = System.currentTimeMillis();
        } else {
            //finish();
            MyActivityManager.getInstance().exit();
        }
    }

    /**
     * 交易成功背景闪烁
     */
    private int counter = 0;
    private TimerTask paySuccessful ;
    /**
     * 修改显示屏信息
     * @param msg
     */
    private void setMainHint(final Message msg){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (msg.what) {
                    case 1://输出消息
                        Toast toast = Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT);
                        MyToast.showMyToast(toast, 1000);
                        break;
                    case 2://修改显示屏信息
                        mainHint.setText(msg.obj.toString());
                        break;
                    case 3://清屏
                        clear();
                        break;
                    case 4://离线刷卡成功
                        mainHint.setText("需付款: ¥" + payMoney +"\n\n请刷卡"+"\n\n"+Html.fromHtml("<font color=\"#2b3598\">"+msg.obj.toString()+"</font>"));
                        String consumeTypeStr = consumeType.getText().toString();
                        consumeType.setText(consumeTypeStr.substring(0, consumeTypeStr.indexOf("(") + 1) + (Integer.parseInt(consumeTypeStr.substring(consumeTypeStr.indexOf("(") + 1, consumeTypeStr.indexOf(")"))) + 1) + ")");
                        break;
                    case 5://在线刷卡成功
                        mainHint.setText("需付款: ¥" + payMoney +"\n\n请刷卡"+"\n\n"+Html.fromHtml("<font color=\"#2b3598\">"+msg.obj.toString()+"</font>"));

                        paySuccessful = new TimerTask() {
                            @Override
                            public void run() {
                                if(counter>3){
                                    counter = 0;
                                    this.cancel();
                                }else{

                                    if(counter%2==0){
                                        Message msg = new Message();
                                        msg.what = 8;
                                        setMainHint(msg);


                                    }else {
                                        Message msg = new Message();
                                        msg.what = 9;
                                        setMainHint(msg);
                                    }

                                    counter++;
                                }
                            }
                        };
                        new Timer().schedule(paySuccessful,0,400);

                        break;
                    case 6://付款失败
                        SpannableStringBuilder builder = new SpannableStringBuilder("需付款: ¥" + payMoney +"\n\n请刷卡"+"\n\n"+msg.obj.toString());

                        ForegroundColorSpan redSpan = new ForegroundColorSpan(getResources().getColor(R.color.red));
                        ForegroundColorSpan blueSpan = new ForegroundColorSpan(getResources().getColor(R.color.LoginBlue));

                        builder.setSpan(blueSpan,0,("需付款: ¥" + payMoney +"\n\n请刷卡"+"\n\n").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        builder.setSpan(redSpan,("需付款: ¥" + payMoney +"\n\n请刷卡"+"\n\n").length(),("需付款: ¥" + payMoney +"\n\n请刷卡"+"\n\n"+msg.obj.toString()).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                        mainHint.setText(builder);
                        break;
                    case 7://余额查询失败

                        SpannableStringBuilder builder2 = new SpannableStringBuilder("请刷卡"+"\n\n"+msg.obj.toString());

                        ForegroundColorSpan redSpan2 = new ForegroundColorSpan(getResources().getColor(R.color.red));
                        ForegroundColorSpan blueSpan2 = new ForegroundColorSpan(getResources().getColor(R.color.LoginBlue));

                        builder2.setSpan(blueSpan2,0,("请刷卡"+"\n\n").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        builder2.setSpan(redSpan2,("请刷卡"+"\n\n").length(),("请刷卡"+"\n\n"+msg.obj.toString()).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                        mainHint.setText(builder2);
                        break;
                    case 8://mainHint 背景变红 字体变白
                        mainHint.setBackgroundResource(R.color.red);
                        mainHint.setTextColor(getResources().getColor(R.color.white));

                        break;
                    case 9://mainHint 背景变白 字体变蓝
                        mainHint.setBackgroundResource(R.color.white);
                        mainHint.setTextColor(getResources().getColor(R.color.LoginBlue));
                        break;
                    case 10://修改离线消费次数
                        List<ConsumeInfo> consumeInfos = consumeInfoDao.getAllOffLineConsumeInfo();
                        consumeType.setText((Status.getStatus().isOffLine() ? "离线" : "在线") + "·正常模式(" + consumeInfos.size() + ")");
                        break;
                }
                //文字更新自动滚动到最后一行
                /*int offset=mainHint.getLineCount()*mainHint.getLineHeight();
                if(offset>mainHint.getHeight()){
                    mainHint.scrollTo(0,offset-mainHint.getHeight()+20);
                }*/
            }
        });
    }

    private ConsumeInfo consumeInfo = new ConsumeInfo();//当前consumeInfo
    private String oldCardNo;//上次付款卡号
    private Long oldSaleTime = System.currentTimeMillis();//上次消费时间
    private static int soundId = 0;
    /**
     * 付款逻辑
     */
    private void pay() {

        readCard(new ReadCardCallBack() {
            @Override
            public void execute(String cardNo,String uuid) {

                System.out.println("~~~~~~~~~~~~start付款逻辑~~~~~~~~~~~~~");

                //固定金额模式下同卡消费时间限制
                if (isFixedMoney && cardNo.equals(oldCardNo) && System.currentTimeMillis() - oldSaleTime < interval * 1000) {//不能消费

                    Message msg = new Message();
                    msg.what = 6;
                    msg.obj = "重复消费小于最短时间间隔";
                    setMainHint(msg);

                    return;
                }

                if (!isFixedMoney) {//非固定金额，不再继续等待刷卡
                    timerTask.cancel();
                    timerTask = null;
                }


                //System.out.println(Status.getStatus().isOffLine()?"离线":"在线");
                if (!Status.getStatus().isOffLine()) {
                    //在线消费
                    Map<String, Object> parameters = new HashMap<>();
                    parameters.put("strCardCode", cardNo);
                    parameters.put("decSaleAmt", payMoney);
                    Config config = configDao.getConfig();
                    parameters.put("strPosCode", config.getProperties().get("posCode"));
                    parameters.put("strUser", userCode);
                    parameters.put("strOnLineCode",uuid);
                    System.out.println("strCardCode:" + cardNo.trim() + "|decSaleAmt:" + operate_result.getText().toString().trim() +
                            "|strPosCode:" + config.getProperties().get("posCode") + "|strUser:" + userCode);

                    SoapObject so = WebServiceUtil.getResponse(config, "ProcessSalesEx", parameters, 1000 * 15);

                    if (so != null) {
                        SoapPrimitive sp = (SoapPrimitive) so.getProperty("ProcessSalesResult");
                        WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());

                        System.out.println("结果响应码：" + wsResult.getResultCode());

                        if (wsResult.getResultCode() == 0) {

                            Message msg = new Message();
                            msg.what = 5;
                            msg.obj = "";

                            oldCardNo = cardNo;
                            oldSaleTime = System.currentTimeMillis();

                            //本地保存消费记录
                            consumeInfo.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                            consumeInfo.setMoney(operate_result.getText().toString().trim());
                            consumeInfo.setCardCode(cardNo);
                            consumeInfo.setVipName("");
                            CardInfo cardInfo = cardInfoDao.getCard(consumeInfo.getCardCode());
                            if (cardInfo != null) {
                                VipInfo vipInfo = vipInfoDao.getVipInfo(cardInfo.getVipId());
                                if (vipInfo != null) {
                                    consumeInfo.setVipName(vipInfo.getVipName());
                                    msg.obj+=vipInfo.getVipName();
                                }
                            }
                            consumeInfo.setDate(DateUtil.getCurDateStr("yyyy.MM.dd HH:mm:ss"));
                            consumeInfo.setIsUpLoad("1");
                            consumeInfoDao.saveConsumeInfo(consumeInfo);

                            String payDate = DateUtil.getCurDateStr("yyyy-MM-dd HH:mm:ss");
                            config.getProperties().put("SHEET_CODE", wsResult.getResultValues().get("SHEET_CODE").toString());
                            config.getProperties().put("payMoney", payMoney);
                            config.getProperties().put("PRINT_ACCT_INFO", wsResult.getResultValues().get("PRINT_ACCT_INFO").toString());
                            config.getProperties().put("payDate", payDate);
                            configDao.saveConfig(config);

                            //播放成功蜂鸣
                            playSound(1,0);
                            msg.obj += "消费成功";
                            setMainHint(msg);
                            System.out.println("在线刷卡成功");

                            if ("true".equals(config.getProperties().get("defaultPrint"))) {
                                //打印小票
                                String[] printInfo = wsResult.getResultValues().get("PRINT_ACCT_INFO").toString().split("\n");
                                printEnd = false;
                                final List<PrintItemObj> data = new ArrayList<PrintItemObj>();

                                data.add(new PrintItemObj("索迪斯餐厅", PrinterConstant.FontScale.FONTSCALE_DW_DH, PrinterConstant.FontType.FONTTYPE_S, PrintItemObj.ALIGN.CENTER, false, 6));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("单据号:" + wsResult.getResultValues().get("SHEET_CODE").toString(), PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                                data.add(new PrintItemObj("POS机号:" + config.getProperties().get("posCode"), PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("===============================", PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("总共消费:" + payMoney, PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("扣款账户", PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                                data.add(new PrintItemObj("\r"));
                                for (String aPrintInfo : printInfo) {
                                    data.add(new PrintItemObj(aPrintInfo, PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                                }
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("===============================", PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("消费时间:" + payDate, PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("\r"));
                                data.add(new PrintItemObj("\r"));
                                print(data);
                            } else {
                                System.out.println("+++++++++休眠1.5s start  "+System.currentTimeMillis()+"++++++++++");
                                try {
                                    Thread.sleep(1500);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                System.out.println("+++++++++休眠1.5s end    "+System.currentTimeMillis()+"++++++++++");
                            }
                        } else {


                            //播放失败蜂鸣
                            playSound(2,0);

                            Message msg = new Message();
                            msg.what = 6;
                            msg.obj = wsResult.getResultValues().get("message").toString();

                            setMainHint(msg);

                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                    } else {
                        //播放失败蜂鸣
                        playSound(2,1);
                        Message msg = new Message();
                        msg.what = 6;
                        msg.obj = "连接超时";

                        setMainHint(msg);

                    }
                } else {//离线消费

                    //判断是否可以消费
                    boolean flag = complexBiz.isSale(cardNo);
                    if (flag) {

                        oldCardNo = cardNo;
                        oldSaleTime = System.currentTimeMillis();


                        Message msg = new Message();
                        msg.what = 5;
                        msg.obj = "";

                        //保存消费记录
                        consumeInfo.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                        consumeInfo.setMoney(payMoney);
                        consumeInfo.setCardCode(cardNo);
                        consumeInfo.setVipName("");
                        CardInfo cardInfo = cardInfoDao.getCard(consumeInfo.getCardCode());
                        if (cardInfo != null) {
                            VipInfo vipInfo = vipInfoDao.getVipInfo(cardInfo.getVipId());
                            if (vipInfo != null) {
                                consumeInfo.setVipName("");
                                msg.obj+=vipInfo.getVipName();
                            }
                        }
                        consumeInfo.setDate(DateUtil.getCurDateStr("yyyy.MM.dd HH:mm:ss"));
                        consumeInfo.setIsUpLoad("0");
                        consumeInfoDao.saveConsumeInfo(consumeInfo);


                        //播放成功蜂鸣
                        playSound(1,0);

                        //离线消费次数显示更改
                        Message message = new Message();
                        message.what = 10;
                        setMainHint(message);
                        //离线消费成功提示
                        msg.obj += "离线刷卡成功";
                        setMainHint(msg);
                        System.out.println("离线刷卡成功");

                        System.out.println("+++++++++休眠1.5s start  "+System.currentTimeMillis()+"++++++++++");
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("+++++++++休眠1.5s end    "+System.currentTimeMillis()+"++++++++++");

                    } else {

                        System.out.println("此卡禁止消费");

                        //播放失败蜂鸣
                        playSound(2,0);

                        Message msg = new Message();
                        msg.what = 6;
                        msg.obj = "此卡禁止消费";
                        setMainHint(msg);


                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }


                }
                System.out.println("~~~~~~~~~~~~end付款逻辑~~~~~~~~~~~~~");
            }
        });
    }

    //倒序转换编号   C32210B8->B81022C3
    private String getCardNo(String cardStr) {
        return cardStr.substring(6) + cardStr.substring(4, 6) + cardStr.substring(2, 4) + cardStr.substring(0, 2);
    }

    private boolean printEnd = true;
    /**
     * 打印小票
     *
     * @param data
     */

    private void print(final List<PrintItemObj> data) {
        try {

            final AidlPrinter aidlPrinter = AidlPrinter.Stub.asInterface(aidlDeviceService.getPrinter());

            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (aidlPrinter != null) {
                        try {
                            aidlPrinter.open();

                            aidlPrinter.printText(data);

                            aidlPrinter.start(new AidlPrinterListener.Stub() {

                                @Override
                                public void onPrintFinish() throws RemoteException {
                                    Log.e(TAG, "打印结束");
                                    printEnd = true;
                                }

                                @Override
                                public void onError(int errorCode) throws RemoteException {
                                    Log.e(TAG, "打印异常");
                                }
                            });
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.e(TAG, "未检测到打印机模块访问权限");
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 播放声音
     * @param sound
     * @param number
     */
    public void playSound(int sound, int number) {
        AudioManager am = (AudioManager) this
                .getSystemService(Context.AUDIO_SERVICE);
        float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volumnCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        float volumnRatio = volumnCurrent / audioMaxVolumn;


        if(sound==1||sound==2){
            soundPool.play(sounddata.get(sound),
                    volumnRatio,// 左声道音量
                    volumnRatio,// 右声道音量
                    1, // 优先级
                    number,// 循环播放次数
                    1);// 回放速度，该值在0.5-2.0之间 1为正常速度
        }else{
            soundPool.play(sounddata.get(sound),
                    0.2f,// 左声道音量
                    0.2f,// 右声道音量
                    1, // 优先级
                    number,// 循环播放次数
                    1);// 回放速度，该值在0.5-2.0之间 1为正常速度
        }


    }


    /**
     *
     * @param isSuccessful
     */
    private void playMedia(Boolean isSuccessful) {
        AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        final int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        if (soundPool == null) {

        } else {
            if (soundId > 0) {
                soundPool.unload(soundId);
            }
            if(isSuccessful){
                soundId = soundPool.load(MainActivity.this, R.raw.di, 1);
            }else{
                soundId = soundPool.load(MainActivity.this, R.raw.di_error, 1);
            }

            //System.out.println("========================="+soundId);
            soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                    //System.out.println("----------------------"+sampleId);
                    soundPool.play(sampleId, maxVolume, maxVolume, 1, 0, 1);
                }
            });
        }
    }

    private TimerTask timerTask;

    /**
     * 读卡
     * @param callBack 读卡后的回调
     */
    private void readCard(final ReadCardCallBack callBack){

        try {

            if(timerTask!=null){
                timerTask.cancel();
                timerTask = null;
            }

            /*
                刷卡
            */
            if (aidlRFCard != null) {

                //等待刷卡10s  固定金额一直等待  间隔0.5s
                final Integer[] count = {0};

                timerTask = new TimerTask() {//每0.2s检测是否存在ic卡
                    @Override
                    public void run() {
                        if (!isFixedMoney) {//固定金额不加
                            count[0]++;
                        }
                        if (count[0] < 20) {
                            try {
                                if (aidlRFCard.isExist() && printEnd) {//存在ic卡

                                    //获得卡号
                                    System.out.println("==========读卡开始========");
                                    Long startTime = System.currentTimeMillis();
                                    int type = aidlRFCard.getCardType();
                                    if(type!=-4){


                                        /*byte blockaddr = 1;
                                        byte[] blockdata = new byte[16];

                                        int result = aidlRFCard.readBlock(blockaddr,blockdata);
                                        System.out.println("读块数据："+String.valueOf(result)+"值"+ISOUtils.hexString(blockdata));


                                        String cardNo = new BigInteger(getCardNo(ISOUtils.hexString(blockdata)), 16).toString();
                                        //执行回调逻辑
                                        callBack.execute(cardNo);*/

                                        byte[] result = aidlRFCard.reset(type);
                                        System.out.println("==========读卡结束========耗时" + (System.currentTimeMillis() - startTime));
                                        Log.i(TAG, " 卡片类型：" + String.valueOf(type));
                                        Log.i(TAG, " 返回卡片序列号：" + (result == null ? "null" : ISOUtils.hexString(result)));
                                        if (result != null) {

                                            String cardNo = new BigInteger(getCardNo(ISOUtils.hexString(result)), 16).toString();

                                            String uuid=UUID.randomUUID().toString().replaceAll("-", "");
                                            //执行回调逻辑
                                            callBack.execute(cardNo,uuid);
                                        }
                                    }else{

                                        System.out.println("读卡失败");

                                        //播放失败蜂鸣
                                        playSound(2,0);

                                        Message msg = new Message();
                                        msg.what = 6;
                                        msg.obj = "读卡失败";
                                        setMainHint(msg);
                                        Thread.sleep(2000);

                                    }
                                } else {
                                    System.out.println("请放卡" + Thread.currentThread().toString());
                                }
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {

                            if (!isFixedMoney) {
                                this.cancel();
                                timerTask = null;
                            }
                        }
                    }
                };
                System.out.println("开始执行消费逻辑");
                new Timer().schedule(timerTask, 0, 500);

            } else {
                Log.e(TAG, "未检到非接读卡设备实例");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
